package com.zeekr.util;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: e-Yuanping.Yang1
 * @time: 2024/6/17 13:31
 */
@Slf4j
public class ExcelUtils {

    public static void export(HttpServletResponse response, String fileName, List<?> projects, String[] columnNames, String[] keys) throws IOException {
        List<Map<String,Object>> collect = projects.stream().map(e -> {
            Map<String,Object> map = new HashMap<>(keys.length);
            Class clz = e.getClass();
            Field[] fields = clz.getDeclaredFields();
            PropertyDescriptor pd = null;
            for(Field field:fields){
                try {
                    for (String key : keys) {
                        if (field.getName().equals(key)) {
                            pd = new PropertyDescriptor(field.getName(), e.getClass());
                            //得到get方法
                            Method get = pd.getReadMethod();
                            Object getValue = get.invoke(e, new Object[]{});
                            map.put(key, getValue);
                        }
                    }
                } catch (Exception exc) {
                    log.error("导出失败,请检查字段设置,{}",exc.getMessage());
                }
            }
            return map;
        }).collect(Collectors.toList());

        ExcelWriter bigWriter = ExcelUtil.getBigWriter();

        for (int i = 0; i < columnNames.length; i++) {
            bigWriter.addHeaderAlias(keys[i],columnNames[i]);
            bigWriter.setColumnWidth(i, 20);
        }
        // 一次性写出内容，使用默认样式，强制输出标题
        bigWriter.write(collect, true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        bigWriter.flush(out, true);
        // 关闭writer，释放内存
        bigWriter.close();
    }

    /**
     * 读取excel表格内容返回List<Bean>
     * @param inputStream  excel文件流
     * @param head         表头数组
     * @param headerAlias  表头别名数组
     * @return
     */
    public static <T>List<T> importExcel(InputStream inputStream, String[] head, String[] headerAlias, Class<T> bean){
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Object> header=reader.readRow(0);
        //替换表头关键字
        if(ArrayUtil.isEmpty(head)|| ArrayUtil.isEmpty(headerAlias)||head.length!=headerAlias.length){
            return null;
        }else{
            for(int i=0;i<head.length;i++){
                if(head[i].equals(header.get(i))){
                    reader.addHeaderAlias(head[i],headerAlias[i]);
                }else{
                    return null;
                }

            }
        }
        //读取指点行开始的表数据（从0开始）
        List<T> read = reader.read(0,1,bean);
        return read;
    }
}
